package com.shanshan.dubborpc.netty;

import com.shanshan.dubborpc.provider.HelloServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @Description 服务器Handler
 * @ClassName NettyServerHandler
 * @Author 山山大魔王
 * @Date 2022/9/2 13:59
 * @Version 1.0
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 获取客户端发送的消息，并调用服务
        System.out.println("msg= " + msg);

        // 客户端再调用服务器的api 时， 我们需要定义一个协议
        // 比如我们要求 每次发消息要以某个字符串开头 "HelloService#hello#"
        if (msg.toString().startsWith("HelloService#hello#")){
            String result = new HelloServiceImpl().hello(msg.toString().substring("HelloService#hello#".length()));

            ctx.writeAndFlush(result);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
